const { getUserData } = require('../../../model/user');
const { fetchOrderList } = require('../../../services/order/orderList');
const config = require('../../../utils/config');

Page({
  data: {
    role: '', // 用户角色
    orders: [],
    tabs: ['全部', '已支付', '已发货', '已取消'],
    activeTab: 0, // 当前选中的 tab 索引
    orderStatusMap: {
      PAYED: '已支付',
      SHIPPED: '已发货',
      CANCELED: '已取消'
    }
  },
  onShow() {
    const userData = getUserData();
    const role = userData.info.role;
    this.setData({
      role,
    });
    this.fetchOrders('全部'); // 默认获取全部订单
  },
  async fetchOrders(status) {
    const user = getUserData();
    if (!user.info.id) {
      wx.showToast({
        title: '用户未登录',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    try {
      const data = await fetchOrderList(user.info.id, status);
      const orders = data.map(order => ({
        imageUrl: `${config.backendUrl}${order.wine.product.imageUrl}`,
        name: order.wine.product.name,
        remarks: order.remarks,
        description: order.wine.product.description,
        totalPrice: order.totalPrice.toFixed(2),
        wineNum: order.wineNum,
        orderId: order.channelOrderId || '无',
        shippingCode: order.shippingCode || '无',
        buyer: order.user.username,
        buyerPhone: order.user.phone,
        orderStatus: this.data.orderStatusMap[order.status] || '未知状态' 
      }));
      this.setData({ orders });
    } catch (error) {
      wx.showToast({
        title: error.message,
        icon: 'none',
        duration: 2000
      });
    }
  },
  
  // 切换 Tab 并调用服务器获取数据
  onTabChange(event) {
    const index = event.currentTarget.dataset.index;
    const statusMap = {
      0: '全部',
      1: 'PAYED',    // 假设“已支付”对应 PAYED
      2: 'SHIPPED',  // 假设“已发货”对应 SHIPPED
      3: 'CANCELED',  // 假设“已取消”对应 CANCLED
    };
    const selectedStatus = statusMap[index];

    this.setData({ activeTab: index });
    this.fetchOrders(selectedStatus); // 直接调用服务器获取筛选后的订单
  },

  goBack() {
    wx.navigateBack();
  }
});
